import { Injectable, Inject, BadRequestException } from '@nestjs/common';
import { Schema } from 'mongoose';

import { DictionaryModel, SubscribeModel } from '@server/models';
import { AuthService } from '@server/auth';
import { BaseResponse } from '@server/basic-dto';
import { DIC_TYPE_CODE_NOT_EXIST } from '@server/modules/dictionary/error';

import { CreateSubscribeDto, QuerySubscribeResponse } from './dto';

@Injectable()
export default class SubscribeService {
  constructor(
    private readonly authService: AuthService,
    @Inject('DICTIONARY_MODEL')
    private readonly dictionaryModel: typeof DictionaryModel,
    @Inject('SUBSCRIBE_MODEL')
    private readonly subscribeModel: typeof SubscribeModel,
  ) {}

  async addSubscribe(
    createSubscribe: CreateSubscribeDto,
  ): Promise<BaseResponse> {
    const count: number = await this.dictionaryModel.countDocuments({
      _id: createSubscribe.locale,
    });

    if (count === 0) {
      throw new BadRequestException(DIC_TYPE_CODE_NOT_EXIST);
    }

    await this.subscribeModel.create(createSubscribe);

    return {
      code: 0,
      message: '',
    };
  }

  async list(
    page: number = 1,
    pageSize: number = 10,
  ): Promise<QuerySubscribeResponse> {
    const data: any = await this.subscribeModel.paginate({
      page: parseInt(`${page}`),
      limit: parseInt(`${pageSize}`),
    });

    return {
      code: 0,
      message: '',
      data,
    };
  }
}
